#pragma once
#include <iostream>
#include <string>
#include <unordered_map>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

using namespace std;
class user
{
public:
    user(const string &ip, const uint16_t &port) : _ip(ip), _port(port) {}
    string &getIp()
    {
        return _ip;
    }
    uint16_t &getPort()
    {
        return _port;
    }

private:
    string _ip;
    uint16_t _port;
};

class userManager
{
public:
    void insert(const string &ip, const uint16_t &port)
    {
        string id = ip + "-" + to_string(port);
        _um.insert(make_pair(id, user(ip, port)));
    }
    void erase(const string &ip, const uint16_t &port)
    {
        string id = ip + "-" + to_string(port);
        _um.erase(id);
    }
    bool isOnline(const string &ip, const uint16_t &port)
    {
        string id = ip + "-" + to_string(port);
        return _um.find(id) == _um.end() ? false : true;
    }
    void broadcast(int sockfd, const string &ip, const uint16_t &port, const string &message)
    {
        for (auto &user : _um)
        {
            struct sockaddr_in addr;
            bzero(&addr, sizeof(addr));
            addr.sin_family = AF_INET;
            addr.sin_port = htons(user.second.getPort());
            addr.sin_addr.s_addr = inet_addr(user.second.getIp().c_str());
            string response = "[" + ip + "]" + "[" + to_string(port) + "]: " + message;
            sendto(sockfd, response.c_str(), response.size(), 0, (sockaddr *)&addr, sizeof(addr));
        }
    }

private:
    unordered_map<string, user> _um;
};